package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author liulei
 * @since 2021-01-08
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * admin登录功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //参数合法性判断
        if(dto==null || dto.getName()==null || dto.getPassword()==null){
            CustException.cust(AppHttpCodeEnum.ADUSER_VALID_ERROR);
        }
        //查询用户
        AdUser adUser=getOne(
                Wrappers.<AdUser>lambdaQuery()
                        .eq(AdUser::getName,dto.getName())
                        .eq(AdUser::getStatus, AdminConstants.AD_USER_ISTAYUS)
        );
        if (adUser==null){
            CustException.cust(AppHttpCodeEnum.ADUSER_NOTEXIST_ERROR);
        }
        //身份校验（密码匹配）
        String dbPwd = adUser.getPassword();
        String salt = adUser.getSalt();
        String pwd = dto.getPassword();
        //加密规则，密码+盐
        String saltPwd=pwd+salt;
        String digest = DigestUtils.md5DigestAsHex(saltPwd.getBytes());

        if (!dbPwd.equals(digest)){
            CustException.cust(AppHttpCodeEnum.ADUSER_NAMEORPWD_ERROR);
        }

        //更新登录时间
        adUser.setCreatedTime(new Date());
        updateById(adUser);
        //生成token并封装结果
        Map<String, Object> resultMap=new HashMap<>();
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        resultMap.put("token",token);
        //清空敏感信息，保护数据
        adUser.setPassword(null);
        adUser.setSalt(null);
        resultMap.put("user",adUser);

        return ResponseResult.okResult(resultMap);
    }

    /**
     * admin注册功能不对外开放
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult register(AdUser user) {
        //参数合法性检查
        if (user==null || StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.ADUSER_VALID_ERROR,"账号密码不能为空");
        }
        // TODO 用户名或用户邮箱唯一性判断

        //MD5+加盐加密
        String salt= UUID.randomUUID().toString().replace("-","");
        String pwd = user.getPassword();
        //封装用户
        user.setSalt(salt);
        user.setPassword(DigestUtils.md5DigestAsHex((pwd+salt).getBytes()));
        user.setCreatedTime(new Date());
        user.setStatus(9);

        save(user);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
